/**
* name: http服务
* describe: 对http请求做统一处理
*/
import {Injectable, Optional} from '@angular/core';
import {Http, Response, Headers} from '@angular/http';
import { RequestOptions } from '@angular/http';
import {SessionStorage} from '../../tools/session.storage';
import 'rxjs/add/operator/toPromise';
import {UniConfigService} from '../config/uni-config.service';
@Injectable()
export class HttpInterceptorBidService {
 // constructor(private http: Http , private config: UniConfigService) { }
  constructor(private http: Http , private config: UniConfigService,
    @Optional() public authHeaders: Headers,
              @Optional() public storage: SessionStorage) {
  }
 /**
  * 统一发送请求
  * @param params
  * @returns {Promise<{success: boolean, msg: string}>|Promise<R>}
  */
 public request(params: any): any {
   this.storage = new SessionStorage();
   this.authHeaders = new Headers();
   this.setToken(params);
   // POST请求（参数、返回值类型都是任意类型)
   params['url'] = this.config.HOSTURL_BID + params['url'];
  //  params['url'] = params['url'];
    console.log(params['url']);
   if (params['method'] === 'post' || params['method'] === 'POST') {
     return this.post(params['url'], params['data']);
   } else if (params['method'] === 'get' || params['method'] === 'GET') {
     // 其他请求
     return this.get(params['url'], params['data']);
   } else if (params['method'] === 'delete' || params['method'] === 'DELETE') {
     return this.delete(params['url']);
   }else if (params['method'] === 'deleteByParam') {
     return this.deleteByParam(params['url'], params['header'], params['data']);
   } else {
    return this.update(params['url'], params['data']);
   }
 }
 /**
  * get请求
  * @param url 接口地址
  * @param params 参数传递
  * @returns {Promise<R>|Promise<U>}
  */
 public get(url: string, params: any): any {
   return this.http.get(url, {search: params})
     .toPromise()
     .then(this.handleSuccess)
     .catch(res => this.handleError(res));
 }
 /**
  * post请求
  * @param url 接口地址
  * @param params 参数
  * @returns {Promise<R>|Promise<U>}
  */
 public post(url: string, params: any) {
  // token 加入header里
  let options = new RequestOptions({ headers: this.authHeaders });
   return this.http.post(url, params, options)
     .toPromise()
     .then(this.handleSuccess)
     .catch(res => this.handleError(res));
 }
 /**
  * update请求
  * @param url 接口地址
  * @param params 参数
  * @returns {Promise<R>|Promise<U>}
  */
  public update(url: string, params: any) {
    return this.http.put(url, params)
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }
  /**
  * delete 请求
  * @param url 接口地址
  * @param params 参数
  * @returns {Promise<R>|Promise<U>}
  */
  public delete(url: string) {
    return this.http.delete(url)
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res));
  }

  /**
   * delete 带body传参
   * @param {string} url
   * @param headers
   * @param params
   * @returns {Promise<{success: boolean; msg: string} | never | Response>}
   */
  public deleteByParam(url: string, headers: any, params: any) {
    return this.http.delete(url, new RequestOptions({
      headers: headers,
      body: params
    }))
    .toPromise()
    .then(this.handleSuccess)
    .catch(res => this.handleError(res));
  }
 /**
  * 处理请求成功
  * @param res
  * @returns {{data: (string|null|((node:any)=>any)}}
*/
 private handleSuccess(res: Response) {
   let body = res['_body'];
   // console.log("接口返回的成功信息：" + body)
   if (body) {
     // 有数据返回
     return {
       resultValue: res.json().resultValue,
       body: body,
       data: res.json().data || {}, // 返回内容
       code: res.json().code || {}, // 返回code
       message: res.json().message || {}, // 返回信息
       statusText: res.statusText,
       status: res.status,
       resultHint: res.json().resultHint,
       type: res.json().type,
       success: res.json().successful
     };
   } else { // 无数据返回
     return {
       data: res.json().data || {}, // 返回内容
       code: res.json().code || {}, // 返回code
       message: res.json().message || {}, // 返回信息
       statusText: res.statusText,
       status: res.status,
       success: true
     };
   }
 }
 /**
  * 处理请求错误
  * @param error
  * @returns {void|Promise<string>|Promise<T>|any}
  */
 private handleError(error) {
   console.log(error);
   let msg = '请求失败';
   if (error.status === 400) {
     console.log('请求参数正确');
   }
   if (error.status === 404) {
     console.error('请检查路径是否正确');
   }
   if (error.status === 500) {
     console.error('请求的服务器错误');
   }
   console.log(error);
   return {success: false, msg: msg};
 }

  /**
   * setToken
   * @param error
   * @returns {void|Promise<string>|Promise<T>|any}
   */
  private setToken(params) {

        var token ;
        token = this.storage.getJson('tokenId');

        if(token===null||JSON.stringify(token)=='{}'){
          // demo
          token = '164563b0-45e7-4b0c-83b9-1cd9d4e4c0e6';
        }

        // header
        this.authHeaders.append('token', token);
        // body
        if(params['data']===null||params['data']===undefined){
          params['data'] = {};
        }
        params['data']['token'] = token;
  }
}
